package com.tarena.elts.net;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Method;
import java.net.Socket;

public class Utils {
	public static Response call(Object obj,Request req){
		Response res = new Response();
		try {
			Class cls = obj.getClass();
			Method method = cls.getDeclaredMethod(req.getMethod(), req.getParamTypes());
			Object val = method.invoke(obj, req.getParams());
			res.setValue(val);
			return res;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			res.setE(e);
		}
		return res;
	}
	public static Response remoteCall(String host,int port , Request req){
		try {
			Socket s = new Socket(host,port);
			ObjectOutputStream out = new ObjectOutputStream(s.getOutputStream());
			System.out.println("remoteCall request"+ req);
			out.writeObject(req);
			out.flush();
			
			ObjectInputStream in = new ObjectInputStream(s.getInputStream());
			Response res = (Response)in.readObject();
			System.out.println("remoteCall Response:"+res);
			s.close();
			return res;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}
}
